<template>
  <div class="pet-widget" :class="pet.state"
    :style="{ left: pet.position.left + 'px', bottom: pet.position.bottom + 'px' }" @mousedown.stop="onDragStart"
    @touchstart.stop="onTouchStart" @click="toggleState">
    <img :src="currentGif" alt="宠物" class="pet-image" />
    <!-- 需要弹一句欢迎时再开 -->
    <!-- <div v-if="pet.state==='greeting'" class="greeting">{{ pet.greeting }}</div> -->
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { usePetStore, type Pet } from '@/stores/pet'

const props = defineProps<{
  petInit?: Partial<Pet>
}>()

const router = useRouter()
const petStore = usePetStore()
const { pet, currentGif } = storeToRefs(petStore)

// 初始化：只从前端拿，绝不请求
onMounted(() => {
  if (props.petInit) petStore.patch(props.petInit)
})

/** —— 打招呼定时器 —— */
let greetTimer: number | null = null
function startGreeting() {
  if (greetTimer) return // 已在打招呼中，直接忽略
  petStore.setState('greeting')
  greetTimer = window.setTimeout(() => {
    petStore.setState('normal')
    greetTimer = null
  }, 2000)
}
function clearGreetingTimer() {
  if (greetTimer) {
    clearTimeout(greetTimer)
    greetTimer = null
  }
}

/** 拖拽逻辑（直接写 pinia） */
let dragging = false
let dragStart = { x: 0, y: 0 }
let widgetStart = { left: 0, bottom: 0 }

const onDragStart = (e: MouseEvent) => {
  if (e.button !== 0) return
  dragging = true
  // 拖拽时中断打招呼，以免状态错乱
  clearGreetingTimer()

  dragStart = { x: e.clientX, y: e.clientY }
  widgetStart = { ...pet.value.position }
  document.addEventListener('mousemove', onDragging)
  document.addEventListener('mouseup', onDragEnd)
}

const onDragging = (e: MouseEvent) => {
  if (!dragging) return
  const dx = e.clientX - dragStart.x
  const dy = e.clientY - dragStart.y
  petStore.setPosition({
    left: Math.max(0, widgetStart.left + dx),
    bottom: Math.max(0, widgetStart.bottom - dy)
  })
}

const onDragEnd = () => {
  dragging = false
  document.removeEventListener('mousemove', onDragging)
  document.removeEventListener('mouseup', onDragEnd)

  if (pet.value.position.left < 40 || pet.value.position.left > window.innerWidth - 140) {
    petStore.setState('hidden')
  } else {
    // 拖拽结束时不自动进入 greeting，保持 normal（或保持原状态）
    petStore.setState('normal')
  }
}

// 移动端拖拽
let touchStart = { x: 0, y: 0 }
const onTouchStart = (e: TouchEvent) => {
  dragging = true
  clearGreetingTimer()
  const t = e.touches[0]
  touchStart = { x: t.clientX, y: t.clientY }
  widgetStart = { ...pet.value.position }
  document.addEventListener('touchmove', onTouchMove, { passive: false })
  document.addEventListener('touchend', onTouchEnd)
}
const onTouchMove = (e: TouchEvent) => {
  if (!dragging) return
  const t = e.touches[0]
  const dx = t.clientX - touchStart.x
  const dy = t.clientY - touchStart.y
  petStore.setPosition({
    left: Math.max(0, widgetStart.left + dx),
    bottom: Math.max(0, widgetStart.bottom - dy)
  })
}
const onTouchEnd = () => {
  dragging = false
  document.removeEventListener('touchmove', onTouchMove)
  document.removeEventListener('touchend', onTouchEnd)
  if (pet.value.position.left < 40 || pet.value.position.left > window.innerWidth - 140) {
    petStore.setState('hidden')
  } else {
    petStore.setState('normal')
  }
}

/** 点击切换逻辑 */
const toggleState = () => {
  if (dragging) return

  const s = pet.value.state
  if (s === 'hidden') {
    // 从隐藏 → 打招呼 → 2s 后进入 normal
    startGreeting()
    return
  }
  if (s === 'greeting') {
    // 打招呼期间的点击忽略
    return
  }
  if (s === 'normal') {
    // 已在 normal，点击进入聊天页
    router.push({ name: 'pet-chat' })
  }
}

onBeforeUnmount(() => {
  clearGreetingTimer()
})
</script>


<style scoped>
.pet-widget {
  position: fixed;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 9999;
  user-select: none;
  transform-origin: left bottom;
  /* 关键点：缩放围绕左下角 */
}

.pet-widget.hidden {
  transform: scale(0.7);
}

.pet-widget.normal {
  transform: scale(1);
  opacity: 1;
}

.pet-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.greeting {
  padding: 0;
  background: none;
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  text-align: center;
  pointer-events: none;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .35), 0 0 10px rgba(0, 0, 0, .25);
}
</style>
